<?php

namespace app\controller\api;

use app\BaseController;
use think\facade\Db;
use think\Request;

class HistoryController extends BaseController
{

    public function addSearch()
    {
        $company_name = input("company_name");
        $result = app('auth')->user();

        $admin_id = $result['id'];
        $url = 'http://192.168.10.190:8211/query_product_catgory/';

        $configData = Db::name("config")->where("admin_id", $admin_id)->select()->toArray();
        if (!$configData) {
            return retError("请前往配置管理中配置");
        }
        $user_ing_task = Db::name("task")->where("admin_id", $admin_id)->where("status", 0)->count();
        if ($user_ing_task > 0) {
            return retError("您有任务在进行中,请等待完成后添加");
        }
        $newArr = [];
        foreach ($configData as $k => $v) {
            $newArr[$v['name']] = $v['value'];
        }

        $newArr['company_name'] = $company_name;
        $result = sendCurlPostRequest($url, $newArr);
        if ($result) {
            $execData = json_decode($result, true);
            if ($execData['code'] == 200) {
                $newArr['uid'] = $execData['uid'];
                $newArr['admin_id'] = $admin_id;
                $newArr['create_time'] = time();
                $task_id = Db::name("task")->insertGetId($newArr);
                return retJson($task_id);
            } else {
                return retError("创建任务失败");
            }
        } else {
            return retError("请求失败");
        }
    }

    public function getList(Request $request)
    {
        $page = input("pageNo");
        $title = input("title");
        $size = input("pageSize");
        $result = app('auth')->user();

        $where = '';
        if ($title) {
            $where = "company_name like '%$title%'";
        }

        $result = Db::name("task")
            ->where($where)
            ->where("admin_id", $result['id'])
            ->field("id,company_name,uid,create_time,update_time,content,admin_id,status")
            ->order("id desc")
            ->paginate(['list_rows' => $size, 'page' => $page ?: 1])
            ->each(function ($item) {
                if ((time() - $item['create_time']) > 600 && !$item['content']) {
                    Db::name("task")->where("id", $item['id'])->update(['status' => 2]);
                } else {
                    if ($item['content']) {
                        Db::name("task")->where("id", $item['id'])->update(['status' => 1]);
                    } else {
                        Db::name("task")->where("id", $item['id'])->update(['status' => 0]);
                    }
                }
                $item['status'] = Db::name("task")->where("id", $item['id'])->value('status');
                $item['content'] = '';
                $item['nickname'] = Db::name("admin")->where("id", $item['admin_id'])->value("nickname");
                $item['create_time_name'] = date("Y-m-d H:i:s", $item['create_time']);
                $item['update_time_name'] = date("Y-m-d H:i:s", $item['update_time']);
                return $item;
            })->toArray();


        return retJson($result,200,Db::name("task")->getLastSql());

    }

    public function getLastHistoryDetail()
    {
        $result = app('auth')->user();

        $task_info = Db::name("task")->where("admin_id", $result['id'])->where("status in (0,1)")->order("id desc")->select();
        $task_info = $task_info[0] ?? [];
        if(!$task_info){
            return retJson();
        }
        $sql = Db::name("task")->getLastSql();
        if ($task_info['content']) {
            $task_info['content'] = json_decode($task_info['content'], true);

            $tmp = [];
            $arr = [];
            foreach ($task_info['content']['LLM_output_logs'] as $k => $v) {
                $tmp['log'] = $v['content'];
                $tmp['rag'] = $task_info['content']['rag_result'][$k]['content'];
                $tmp['search'] = $task_info['content']['search_result'][$k]['content'];
                $arr[] = $tmp;
            }


            $task_info['detail_result'] = $arr;
//            $task_info['content']['LLM_result_product'] = explode("|", $task_info['content']['LLM_result_product']);
//            $task_info['content']['LLM_result_category'] =  explode("-", $task_info['content']['LLM_result_category']);
        }
        $task_info['create_time_name'] = date("Y-m-d H:i:s", $task_info['create_time']);
        if ($task_info['update_time'] > 0) {
            $task_info['update_time_name'] = date("Y-m-d H:i:s", $task_info['update_time']);
        }
        if ((time() - $task_info['create_time']) > 600 && !$task_info['content']) {
            Db::name("task")->where("id", $task_info['id'])->update(['status' => 2]);
        } else {
            if ($task_info['content']) {
                Db::name("task")->where("id", $task_info['id'])->update(['status' => 1]);
            } else {
                Db::name("task")->where("id", $task_info['id'])->update(['status' => 0]);
            }
        }
        $task_info['nickname'] = Db::name("admin")->where("id", $task_info['admin_id'])->value("nickname");
        return retJson($task_info, 200, $sql);
    }

    public function getDetail(Request $request)
    {
        $id = $request->post("id");
        $task_info = Db::name("task")->where("id", $id)->find();

        if ($task_info['content']) {
            $task_info['content'] = json_decode($task_info['content'], true);

            $tmp = [];
            $arr = [];
            foreach ($task_info['content']['LLM_output_logs'] as $k => $v) {
                $tmp['log'] = $v['content'];
                $tmp['rag'] = $task_info['content']['rag_result'][$k]['content'];
                $tmp['search'] = $task_info['content']['search_result'][$k]['content'];
                $arr[] = $tmp;
            }


            $task_info['detail_result'] = $arr;
//            $task_info['content']['LLM_result_product'] = explode("|", $task_info['content']['LLM_result_product']);
//            $task_info['content']['LLM_result_category'] =  explode("-", $task_info['content']['LLM_result_category']);
        }
        $task_info['create_time_name'] = date("Y-m-d H:i:s", $task_info['create_time']);
        if ($task_info['update_time'] > 0) {
            $task_info['update_time_name'] = date("Y-m-d H:i:s", $task_info['update_time']);
        }
        $task_info['nickname'] = Db::name("admin")->where("id", $task_info['admin_id'])->value("nickname");
        return retJson($task_info);
    }


    public function doDelete()
    {
        $id = input("id");
        $result = Db::name("task")->where("id", $id)->delete();
        return retJson($result);
    }
}
